package com.khalil.kkadmin.infrastructure;

import com.khalil.kkadmin.infrastructure.jpa.KkJpaRepository;

import java.util.List;

public abstract class BaseService<J extends KkJpaRepository<T, K>, T, K> implements IService<T, K> {

    public final J repository;

    public BaseService(J repository) {
        this.repository = repository;
    }

    @Override
    public T findById(K id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<T> findAll() {
        return repository.findAll();
    }


    @Override
    public T create(String json) {
        T entity = str2CreateEntity(json);
        if (entity == null) {
            return null;
        }
        return create(entity);
    }

    @Override
    public T update(String json) {
        T entity = str2UpdateEntity(json);
        if (entity == null) {
            return null;
        }
        return update(entity);
    }

    @Override
    public T create(T t) {
        return repository.save(t);
    }

    @Override
    public T update(T t) {
        return repository.save(t);
    }

    @Override
    public void deleteById(K id) {
        repository.deleteById(id);
    }

    protected abstract T str2CreateEntity(String json);

    protected abstract T str2UpdateEntity(String json);
}
